package com.hzqy.web.ac.epg;

import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.commons.utils.WChatUtils;
import com.hzqy.service.epg.AcUserBillServiceBean;
import com.hzqy.service.epg.BianfengService;
import com.hzqy.service.epg.IptvActivityService;
import com.hzqy.service.epg.WchatService;
import com.hzqy.service.epg.WchatTvOrgService;
import com.hzqy.service.hqjc.ActivityServiceBean;
import com.hzqy.service.hqjc.HqjcServiceBean;
import com.hzqy.service.street.AreaStreetServiceBean;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.AcWinningVo;
import com.hzqy.web.vo.CmContentVo;
import com.hzqy.web.vo.SysAreaStreetVo;
import com.hzqy.web.vo.WchatTvUserVo;
import com.hzqy.web.vo.epg.WchatTvOrgVo;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/mobile/wchatServer")
public class ActivityCardServerAction {
	private static final Log LOG = LogFactory.getLog(ActivityCardServerAction.class);
	private static final String CHARSET = "UTF-8";
	//private static final String key = "#kdVer@zZ";
	private static final String key = SystemConfigUtils.getSysConfig("activityCardKey");;
    @Resource
    private AcUserBillServiceBean serviceBean;
    @Resource
	private AreaStreetServiceBean areaStreetServiceBean;
    @Resource
	private WchatTvOrgService service;
	@Resource
	private ActivityServiceBean activityServiceBean;
	@Resource
	private HqjcServiceBean hqjcServiceBean;
	@Resource
	private IptvActivityService iptvService;
	
    @RequestMapping("/getQRCode")
  	public void getQRCode(HttpServletResponse resp, HttpSession session, String serverId) throws IOException  {
    	String inputStream = WchatService.getORPIC(session,serverId);
        Map<String ,String> map = new HashMap<>();
        map.put("status", "0");
        map.put("QRCode", inputStream);//异常
        serviceBean.printlnOut(resp, "", map);
  	}

	@RequestMapping("/createButton")
	public void createButton(HttpServletResponse resp) throws IOException  {
		String inputStream = WchatService.createSignUp();
		Map<String ,String> map = new HashMap<>();
		map.put("result", inputStream);
		serviceBean.printlnOut(resp, "", map);
	}
	
	/**
	 * 删除自定义菜单
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/delButton")
	public void delButton(HttpServletResponse resp) throws IOException  {
		String inputStream = WchatService.delButton();
		Map<String ,String> map = new HashMap<>();
		map.put("result", inputStream);
		serviceBean.printlnOut(resp, "", map);
	}

	/**
	 *
	 *  边锋重置积分
	 * @param phoneNum 手机号
	 * **/
    @RequestMapping("/getReset")
    @ResponseBody
    public Object getReset(String phoneNum) throws IOException  {
        Map<String,Object> map = new HashMap<String,Object>();
        String reset = BianfengService.postIntegralReset(phoneNum);//公网直接调用
        JSONObject resultJson = JSONObject.parseObject(reset);
        LOG.debug("打印边锋请求重置积分信息返回code："+resultJson.get("code"));
        if("0".equals(String.valueOf(resultJson.get("code")))) {
            map.put("res","sucess");
        }else{
            map.put("res","false");
        }
         return  map;
    }
   
    /**
     * 请求边锋绑定情况
     * @param phone
     * @return  0 已绑定iptvid及边锋账号； 1：未报名；2：报名还未绑定iptvid；3：绑定iptvid，未绑定边锋账号
     * @throws IOException
     */
    @RequestMapping("/getBFBangding")
    @ResponseBody
    public Object  getBFBangding(String phone) throws IOException  {
    	Map<String , Object> map = new HashMap<String,Object>();
    	String BF = BianfengService.getQueryBind(phone);
    	JSONObject resultJson = JSONObject.parseObject(BF);
    	LOG.debug("公网请求边锋绑定情况接口返回："+resultJson);
		map.put("code", resultJson.get("code"));
		map.put("message", resultJson.get("message"));
		map.put("data", resultJson.get("data"));
		return map;
    }
    
    /**
     * 边锋账号手机号绑定
     * @param phone
     * @param serviceId
     * @return  code = 0 绑定成功
     * @throws IOException
     */
    @RequestMapping("/sendBFBangding")
    @ResponseBody
    public Object sendBFBangding(String phone,String serviceId)  throws IOException  {
    	Map<String , Object> map = new HashMap<String,Object>();
    	String BF = BianfengService.postUserBind(phone,serviceId);
    	JSONObject resultJson = JSONObject.parseObject(BF);
    	LOG.debug("公网边锋账号手机号绑定接口返回："+BF);
    	map.put("code", resultJson.get("code"));
		map.put("message", resultJson.get("message"));
		return map;
    }
    /**
     * 查询玩家积分
     * stage：第几期排行，如2019.03.18-2019.04.18为1，2019.04.19-2019.05.19 为2
     * phone：所需查询玩家，可批量，不同玩家之间用英文逗号分隔，如：18888888888,15999999999，一次最大20个
     */
    @RequestMapping("/getBFUserIntegral")
    @ResponseBody
    public Object getBFUserIntegral(String stage, String phone) throws IOException {
    	Map<String , Object> map = new HashMap<String,Object>();
    	String BF = BianfengService.getUserIntegral(stage,phone);
    	JSONObject resultJson = JSONObject.parseObject(BF);
    	map.put("code", resultJson.get("code"));
		map.put("message", resultJson.get("message"));
		map.put("data", resultJson.get("data"));
		return map;
    }
    
    
    /**
     * 用户排行榜接口
     * stage：第几期排行，如2019.03.18-2019.04.18为1，2019.04.19-2019.05.19 为2
     * start：第几名开始取数据
     * top：取出的条数
     * phone：如需要查询当前个人的排行，需要此字段
     */
    @RequestMapping("/getBFUserRank")
    @ResponseBody
    public Object getBFUserRank(String stage, String start, String top, String phone) throws IOException {
    	Map<String , Object> map = new HashMap<String,Object>();
    	String BF = BianfengService.getUserRank(stage,start,top,phone);
    	JSONObject resultJson = JSONObject.parseObject(BF);
    	map.put("code", resultJson.get("code"));
		map.put("message", resultJson.get("message"));
		map.put("data", resultJson.get("data"));
		return map;
    }
    /**
     * 玩家游戏局数
     * phone：所需查询玩家，可批量，不同玩家之间用英文逗号分隔，如：18888888888,15999999999，一次最大20个
     */
    @RequestMapping("/getBFUserPlayCount")
    @ResponseBody
    public Object getBFUserPlayCount(String phone) throws IOException {
    	Map<String , Object> map = new HashMap<String,Object>();
    	String BF = BianfengService.getUserPlayCount(phone);
    	JSONObject resultJson = JSONObject.parseObject(BF);
    	map.put("code", resultJson.get("code"));
		map.put("message", resultJson.get("message"));
		map.put("data", resultJson.get("data"));
		return map;
    }

	/**
	 * 明星赛排行榜
	 * yesterday ： 1，表示拉取昨日数据，不填默认为当日数据
	 */
	@RequestMapping("/selectStarrank")
	@ResponseBody
	public static Map<String , Object> selectStarrank(String yesterday) throws IOException {
		Map<String , Object> map = new HashMap<String,Object>();
		String BF = BianfengService.selectStarrank(yesterday);
		System.out.println(String.valueOf(BF));
		JSONObject resultJson = JSONObject.parseObject(BF);
		map.put("code", resultJson.get("code"));
		map.put("message", resultJson.get("message"));
		map.put("data", resultJson.get("data"));
		return map;
	}

	public static void main(String[] args) throws IOException {
		Map<String , Object> map = new HashMap<String,Object>();
		map = selectStarrank("1");
		System.out.println(map.toString());
		
	}
	@RequestMapping("/selectAreaStreet")
	@ResponseBody
	public Object selectAreaStreet(SysAreaStreetVo sysAreaStreetVo) {
		LOG.debug("enter");
		List<SysAreaStreetVo> areaList= new ArrayList<SysAreaStreetVo>();
		areaList = areaStreetServiceBean.selectAreaStreet(sysAreaStreetVo);
		
		return areaList;
	}
	
	@RequestMapping("/selectById")
	@ResponseBody
	public Object selectById (int f_sas_id) {
		SysAreaStreetVo areaList= new SysAreaStreetVo();
		areaList = areaStreetServiceBean.selectById(f_sas_id);
		return areaList;
	}
	
	@RequestMapping("/selectByName")
	@ResponseBody
	public Object selectByName (SysAreaStreetVo sysAreaStreetVo) {
		SysAreaStreetVo areaList = areaStreetServiceBean.selectByName(sysAreaStreetVo);
		if(areaList == null) {
			areaList = new SysAreaStreetVo();
		}
		return areaList;
	}

	
	@RequestMapping(value = "/insertWchatTvUserInfo")
	@ResponseBody
	public Object insertWchatTvUserInfo(WchatTvUserVo wchatTvUserVo, WchatTvOrgVo wchatTvOrgVo) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (wchatTvUserVo.getF_wtut_serverid() != null && !"".equals(wchatTvUserVo.getF_wtut_serverid().trim()) && !"null".equals(wchatTvUserVo.getF_wtut_serverid())) {
			int sernum = service.selectByIPTV(wchatTvUserVo.getF_wtut_serverid());
			if(sernum >0) {
				map.put("success", false);
				map.put("msg", "该IPTV账号已绑定");
				return map;
			}
		}
		int wchat = service.selectByPhone(wchatTvUserVo.getF_wtut_phone());
		if(wchat <= 0) {
			int flag = service.insertWchatTvUserInfo(wchatTvUserVo, wchatTvOrgVo);
			if (flag > 0 ) {
				try {
					String Bf= BianfengService.postSignUp(wchatTvUserVo.getF_wtut_phone(),wchatTvUserVo.getF_wtut_nickname(), wchatTvOrgVo.getF_wtgo_address(),wchatTvUserVo.getF_wtut_serverid());
					JSONObject resultJson = JSONObject.parseObject(Bf);
					LOG.debug("边锋报名接口返回："+resultJson);
				} catch (IOException e) {
					 e.printStackTrace(); 
				}
				map.put("success", true);
				map.put("msg", "报名成功");
			} else {
				map.put("success", false);
				map.put("msg", "报名失败");
			}
		}else {
			map.put("success", false);
			map.put("msg", "该手机号码已注册");
		}
		
		return map;
	}

	@RequestMapping(value = "/selectWchatTvUserInfo")
	@ResponseBody
	public Object selectWchatTvUserInfo(String f_wtut_openid,String f_wtut_serverid) {
		Map<String,Object> map = new HashMap<String,Object>();
		WchatTvUserVo wchatTvUserVo = new WchatTvUserVo();
		wchatTvUserVo = service.selectWchatTvUserInfo(f_wtut_openid,f_wtut_serverid);
		LOG.debug(wchatTvUserVo+"");
		if(wchatTvUserVo == null) {
			map.put("msg", "false");
			return map;
		}else {
			return  wchatTvUserVo;
		}
	}
	
	/**
	 * 话费兑换
	 */
	@RequestMapping(value = "/telephone")
	@ResponseBody
	public Map<String,String> telephone(String f_wtut_openid){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("f_wtut_openid", f_wtut_openid);
		Map<String,String>  result = service.selectPhoneINFO(map);
		return result;
	}
	
	/**
	 *  微信端修改用户地址
	 * f_awl_activityid 活动id
	 * f_awl_serverid  IPTV账号
	 * f_awl_userphone  用户手机号
	 * f_awl_prizename  奖品+<>+用户姓名+<>+地址
	 * */

    @RequestMapping("/updateAcWining")
    @ResponseBody
    public Object updateAcWining(AcWinningVo awv,HttpServletRequest request,HttpServletResponse response)  throws IOException  {
    	Map<String , Object> map = new HashMap<String,Object>();
		int count = activityServiceBean.updateWinning(awv);
		if(count>0) {
    		map.put("success", true);
			map.put("msg", "提交成功！");
    	}else {
    		map.put("success", false);
			map.put("msg", "提交失败！");
    	}
    	return map;
	}
    /**
	 *  微信端查询用户中奖信息
	 * f_awl_activityid 活动id
	 * f_awl_serverid  IPTV账号
	 * f_awl_prizeid  奖品id
	 * */
    @RequestMapping("/selectUWinningList")
	@ResponseBody
	public Object selectUWinningList(AcWinningVo awv) {
		List<AcWinningVo> uwinningList = activityServiceBean.selectUWinningList(awv);
		return uwinningList;
	}
    /**
	 *  微信端选择奖品
	 * f_awl_activityid 活动id
	 * f_awl_serverid  IPTV账号
	 * f_awl_prizeid  奖品id f_awl_prizename 奖品名称 f_awl_username f_awl_useraddress
	 * return result，-1:奖品已被抢空，>0：成功
	 * */
    @RequestMapping("/updateWinning")
	@ResponseBody
	public Object updateWinning(AcWinningVo awv,int allCount) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	String f_awl_prizeid=awv.getF_awl_prizeid();
    	String f_awl_serverid=awv.getF_awl_serverid();
    	int result=-1;
    	Boolean insertFlat=false;
    	awv.setF_awl_prizeid("");
    	List<AcWinningVo> uwinningList = activityServiceBean.selectUWinningList(awv);//查询该用户 此活动有无中奖
    	if(uwinningList.size()>0){//已中奖 修改
    		awv.setF_awl_activityid("'"+awv.getF_awl_activityid()+"'");
    		result=activityServiceBean.updateWinning(awv);
    	}else{
    		if(allCount ==0){
    			insertFlat=true;
    		}else if(allCount >0){
    			awv.setF_awl_serverid("");
    			awv.setF_awl_prizeid(f_awl_prizeid);
    			List<AcWinningVo> winningList = activityServiceBean.selectUWinningList(awv);//查询此活动此奖品有多少中奖
    			if(winningList.size()<allCount){
    				insertFlat=true;
    			}else{
    				result=-1;
    			}
    		}
    	}
    	if(insertFlat){
			awv.setF_ui_resolution(0);//默认
			Date date=new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time1 = sdf.format(date);
			awv.setF_awl_date(time1);
			awv.setF_awl_serverid(f_awl_serverid);
			awv.setF_awl_prizeid(f_awl_prizeid);
			result=activityServiceBean.insertWinningList(awv);
		}
    	if(result>0){
    		String iptvAccount= awv.getF_awl_serverid();//用户账号
			String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);
			String telephone= awv.getF_awl_userphone();
			String receiver = awv.getF_awl_username();
			String address = awv.getF_awl_useraddress();
			try {
				String iptvResult = iptvService.activityAddressAdd(secretKey, iptvAccount, receiver, telephone, address, "1");
				LOG.debug("iptvResult:"+iptvResult);
			} catch (Exception e) {
				//LOG.debug("收获地址同步异常："+e.getMessage());
			}
    	}
    	map.put("result", result);
		return map;
	}
    /**
     * 微信端获取内容信息
	 * @param f_cc_id
	 * @param f_cc_cprid
	 * @return
	 */
	@RequestMapping("/content")
	@ResponseBody
	public Object selectContent(CmContentVo contentVo) {
		CmContentVo content= hqjcServiceBean.selectContent(contentVo);
		return content;
	}
	/** 插入用户中奖记录
	 * f_awl_activityid 活动id
	 * f_awl_prizeid  奖品id
	 * f_awl_prizename  奖品名称
	 * f_awl_userphone  用户手机号
	 * f_awl_serverid  IPTV账号
	 * 
	 */
	@RequestMapping("/insertAcWining")
	@ResponseBody
	public Object insertAcWining(AcWinningVo awv,int allcount,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
		awv.setF_ui_resolution(0);//默认
		
		List<AcWinningVo> uwlist =activityServiceBean.selectUWinningList(awv);
		System.out.println("uwlist.size():"+uwlist.size());
		if(uwlist!=null && uwlist.size() < allcount) {
			Date date=new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String time1 = sdf.format(date);
			awv.setF_awl_date(time1);
			int counst =activityServiceBean.insertWinningList(awv);
			map.put("count",counst);
			//用户信息同步
			String[] info=awv.getF_awl_prizename().split("<>");
			String iptvAccount= awv.getF_awl_serverid();//用户账号
			String secretKey =epgCommonAction.getEPGSecretKey(iptvAccount);
			String telephone= awv.getF_awl_userphone();
			String receiver= "";
			String address= "";
			if(info.length==3) {
				receiver = info[1];
				address = info[2];
			}else if(info.length==2) {
				receiver = info[1];
				address = telephone;
			}else if(info.length==1) {
				receiver = telephone;
				address = telephone;
			}
			try {
				String resule = iptvService.activityAddressAdd(secretKey, iptvAccount, receiver, telephone, address, "0");
				System.out.println("result:"+resule);
			} catch (Exception e) {
				System.out.println("收获地址同步异常：");
			}
		}else{
			map.put("count",-1);
		}
		return map;
	}
	/**
	 * 获取AccessToken接口
	 *  token:
	 *  companyid:
	 */
	@RequestMapping(value = "/getAccessToken")
	@ResponseBody
	public Object getAccessToken(
			@RequestParam("token") String token,
			@RequestParam("companyid") String companyid
			){
		Map<Object,Object> map = new HashMap<>();
		String getAccessToken_companyid = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.getAccessToken_companyid.getKey());
		Boolean isCompanyid = false;
		if(getAccessToken_companyid != null && !"".equals(getAccessToken_companyid)){
			String [] companyids = getAccessToken_companyid.split(",");
			for(int i=0;i<companyids.length;i++){
				if(companyid.equals(companyids[i])){
					isCompanyid =true;
					break;
				}
			}
		}
		LOG.debug("getAccessToken,companyid="+companyid);
		if(!isCompanyid) {
			map.put("msg","渠道编号认证失败");
			map.put("result", "-2");
			return map;
		}
		String _token = getToken(companyid);
		if("".equals(_token) || !_token.equals(token)) {
			map.put("msg","签名认证失败");
			map.put("result", "-3");
			return map;
		}
		String accessToken = "";
		try {
			accessToken = WchatService.getAccessToken();
			LOG.debug("AccessToken="+accessToken);
		} catch (Exception e) {
			LOG.debug("获取accessToken异常：");
		}
		if("".equals(accessToken) || accessToken == null) {
			map.put("msg", "获取accessToken失败");
			map.put("result", "-1");
			return map;
		}
		map.put("accessToken", accessToken);
		map.put("msg", "获取accessToken成功");
		map.put("result", "1");
		return map;
	}
	public static String getToken(String companyid) {
		String token = "";
		try {
			token = new String(Base64.encodeBase64(DigestUtils.md5((companyid+key).getBytes(CHARSET))), CHARSET);
		} catch (Exception e) {
			LOG.debug("base64+md5加密异常");
		}
		return token;
	}
}